﻿Imports System.IO

' http://stackoverflow.com/questions/230128/best-way-to-copy-between-two-stream-instances-c

Public Module StreamEx

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub CopyTo(ByVal src As Stream, ByVal dest As Stream)
        Dim size As Integer = If((src.CanSeek), Math.Min(CInt(src.Length - src.Position), &H2000), &H2000)
        Dim buffer As Byte() = New Byte(size - 1) {}
        Dim n As Integer
        Do
            n = src.Read(buffer, 0, buffer.Length)
            dest.Write(buffer, 0, n)
        Loop While n <> 0
    End Sub

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub CopyTo(ByVal src As MemoryStream, ByVal dest As Stream)
        dest.Write(src.GetBuffer(), CInt(src.Position), CInt(src.Length - src.Position))
    End Sub

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub CopyTo(ByVal src As Stream, ByVal dest As MemoryStream)
        If src.CanSeek Then
            Dim pos As Integer = CInt(dest.Position)
            Dim length As Integer = CInt(src.Length - src.Position) + pos
            dest.SetLength(length)

            While pos < length
                pos += src.Read(dest.GetBuffer(), pos, length - pos)
            End While
        Else
            src.CopyTo(DirectCast(dest, Stream))
        End If
    End Sub
End Module
